﻿package com.cw.utils
{
	import net.libra.core.Facade;
	import net.libra.notifier.Notification;

	/**
	 * 异步调用方法集
	 * 对象负责按照一定的顺序调用异步方法
	 * 不支持异步和同步方法混合调用
	 * @author DanielLu
	 * 
	 * 先调用model.loginProxy.getRefresh，等LoginProxy.GETREFRESHCOMPLETED消息发出来后，
	 * 然后发一个DELETEREPORTSUCCESS消息.
	 * asy.addAsyncMethod(model.loginProxy.getRefresh, null, LoginProxy.GETREFRESHCOMPLETED);
	 * asy.addAsyncMethod(sendNotification, [DELETEREPORTSUCCESS]);
	 * 
	 * 在没有第三个参数的情况下，每隔20毫秒调用 fun1,fun2
	 * asy.addAsyncMethod(fun1,["jiangbo"]);
	 * asy.addAsyncMethod(fun2,["jiangbo"]);
	 */
	public class AsyncUtils 
	{
		private var _methodList : Array;
		private var _currentIndex : int;
		private var _name:String;
		
		public function AsyncUtils (name:String)
		{
			this._methodList = [];
			this.currentIndex = - 1;
			this._name = name;
			Facade.getInstance().registerAsync(this._name,this);
		}
		/**
		 * 添加要进行异步调用的方法
		 * @param func
		 * @param param
		 * @param resultNotificationName
		 * @param faultNotificationName
		 */
		public function addAsyncMethod (func : Function,param : Array = null,resultNotificationName : String = null,faultNotificationName : String = null) : void
		{
			var obj : Object = {};
			obj.func = func;
			obj.param = param;
			obj.resultNotificationName = resultNotificationName;
			obj.faultNotificationName = faultNotificationName;
			this._methodList.push( obj );
		}

		public function runMethod () : void
		{
			if(this.currentIndex == - 1)
			{
				this.run ();
			}
		}
//		/**
//		 * 运行方法
//		 */
		public function run () : void
		{
			this.currentIndex ++;
			//获取要运行的异步方法
			var obj : Object = this.methodList[this.currentIndex];
			if(obj)
			{
				obj.func.apply( null , obj.param );
			}
			else
			{
				this.currentIndex = - 1;
				Facade.getInstance().removeAsync(this._name);
			}
		}
		
		public function __onResult () : void
		{
			var obj : Object = this.methodList[this.currentIndex];
			//执行下一步
			this.run( );
		}
		
		public function __onFault () : void
		{
			//不再执行
			var obj : Object = this.methodList[this.currentIndex];
			this.currentIndex = - 1;
		}
		
		public function getCurrentMethodObj():Object
		{
			return _methodList[this.currentIndex];
		}
		public function get methodList():Array
		{
			return _methodList;
		}
		
		public function set methodList(value:Array):void
		{
			_methodList = value;
		}
		public function get currentIndex():int
		{
			return _currentIndex;
		}
		
		public function set currentIndex(value:int):void
		{
			_currentIndex = value;
		}
	}
}
